﻿using ProgressTracker.Domain.Contracts;
using ProgressTracker.Domain.Messages;
using ProgressTracker.WebUI.Models.Task;
using System.Web.Mvc;

namespace ProgressTracker.WebUI.Controllers
{
    [Authorize]
    public class TaskController : Controller
    {
        ITaskService _taskService;

        public TaskController(ITaskService taskService)
        {
            _taskService = taskService;
        }

        public ActionResult Index()
        {
            var model = new IndexViewModel
            {
                CurrentTasks = _taskService.GetCurrentTasks(User.Identity.Name),
                NewTaskModel = new AddNewTaskModel()
            };

            return View(model);
        }

        public PartialViewResult Add()
        {
            return PartialView("_Add", new AddNewTaskModel());
        }

        [HttpPost]
        public ActionResult Add(AddNewTaskModel model)
        {
            var request = new AddTaskRequest
            {
                Description = model.Description,
                Name = model.Name,
                UserEmail = User.Identity.Name
            };

            _taskService.AddTask(request);

            return RedirectToAction("Index");
        }

        public ActionResult Archive(int id)
        {
            _taskService.ArchiveTask(id);

            return RedirectToAction("Index");
        }

        public PartialViewResult Edit(int id)
        {
            var task = _taskService.GetTask(id);

            var model = new EditTaskModel
            {
                Id = task.Id,
                Name = task.Name,
                Description = task.Description
            };

            return PartialView("_Edit" ,model);
        }

        [HttpPost]
        public ActionResult Edit(EditTaskModel model)
        {
            var request = new UpdateTaskRequest
            {
                Description = model.Description,
                Id = model.Id,
                Name = model.Name
            };

            _taskService.UpdateTask(request);

            return RedirectToAction("Index");
        }
	}
}